<?php

/**
 * SimplifyPHP Framework
 *
 * This file is part of SimplifyPHP Framework.
 *
 * SimplifyPHP Framework is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * SimplifyPHP Framework is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @author Rodrigo Rutkoski Rodrigues, <rutkoski@gmail.com>
 */

class AutoRouterImpl extends AbstractApplicationComponent
{

  /**
   * 
   * @var array
   */
  protected $parsed = array();

  /**
   * 
   * @var ICache
   */
  protected $cache;

  /**
   * 
   * @var string
   */
  protected $cacheid = 'Simplify/Router/Routes/Auto';

  public function build($route, $params)
  {
  }

  public function parse($route)
  {
    $base = $this->config->get('routing:home:dir');
    
    $words = preg_split('#/#', $route, - 1, PREG_SPLIT_NO_EMPTY);
    
    /**
     * find path
     */
    
    $path = '/';
    
    $dir = $this->config->get('routing:home:controller');
    
    while (count($words) && is_dir($base . $path . $words[0])) {
      $dir = $words[0];
      $path .= array_shift($words);
    }
    
    /**
     * find controller
     */
    
    if (count($words)) {
      $file = $base . $path . '/' . $words[0] . '_controller.php';
      
      if (file_exists($file)) {
        $controller = array_shift($words);
      }
    }
    
    if (empty($controller)) {
      $file = $base . $path . '/' . $dir . '_controller.php';
      
      if (! file_exists($file)) {
        throw new RouterException('Controller not found: ' . $file);
      }
      
      $controller = $dir;
    }
    
    require_once ($file);
    
    $class = Inflector::classify($controller . '_controller');
    
    if (! class_exists($class)) {
      throw new RouterException('Class not found: ' . $class);
    }
    
    /**
     * find action
     */
    
    if (count($words) && method_exists($class, 'action_' . $words[0])) {
      $action = array_shift($words);
    }
    else {
      $action = 'index';
    }
    
    $params = count($words) ? $words : array();
    
    $real_route = $path . '/' . $controller . '/' . $action . '/' . implode('/', $params);
    
    return new ParameterHolder(array(
      'path' => $base . $path, 'controller' => $controller, 'action' => $action, 'params' => $params 
    ));
  }

}

?>